package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.Util.ValidateAdd;
import com.project.Util.ValidateUpdate;
import com.project.bean.UserManBean;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping("userMan")
public class UserManController {

    /**
     * 添加用户（带springMVC验证）
     *
     * @param userManBean Valid注解标识该属性必须进行验证
     * @param result      用于判断验证是否通过，以及绑定出错信息
     * @return
     */
    @RequestMapping("add")
    public String add(@Validated(ValidateAdd.class) UserManBean userManBean, BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()) {
            List<FieldError> errors = result.getFieldErrors();
            //将注解信息转化为json字符串
            ObjectMapper om = new ObjectMapper();
            String error = om.writeValueAsString(errors);
            return error;
        }
        System.out.println(userManBean);
        System.out.println("执行添加业务");
        return "ok";
    }

    @RequestMapping("update")
    public String update(@Validated(ValidateUpdate.class) UserManBean userManBean, BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()) {
            List<FieldError> errors = result.getFieldErrors();
            //将注解信息转化为json字符串
            ObjectMapper om = new ObjectMapper();
            String error = om.writeValueAsString(errors);
            return error;
        }
        System.out.println(userManBean);
        System.out.println("执行添加业务");
        return "ok";
    }
}
